package com.tfswx.jkgl.core.cscl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tfswx.jkgl.core.cscl.base.CsclBase;
import com.tfswx.jkgl.core.utils.ServiceUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author ricky
 * @date 2021/12/17
 */
@Component
public class GetValueFromToken implements CsclBase {
    @Override
    public String getName() {
        return "执行方法获取指定值";
    }

    @Override
    public boolean sfxycs() {
        return true;
    }

    @Override
    public Object encode(Object value, Object jmcs, String pBds, String id) {
        String jmcsStr = String.valueOf(jmcs);
        if (StringUtils.isBlank(jmcsStr)) {
            throw new RuntimeException(getName() + "需要参数");
        }
        JSONObject jsonObject = JSON.parseObject(jmcsStr);
        String url = jsonObject.getString("url");
        if (StringUtils.isBlank(url)) {
            throw new RuntimeException("策略参数url-不能为空");
        }
        String val = jsonObject.getString("val");
        if (StringUtils.isBlank(val)) {
            throw new RuntimeException("策略参数val-不能为空");
        }
        // url = UrlUtil.getUrl(url);
        // HttpHeaders headers = UrlUtil.getHeaders();
        // HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        // Object o = HttpUtil.apiPostForObject(url, httpEntity);
        String[] split = url.split("\\.");
        if (split.length != 2) {
            throw new RuntimeException("url配置不正确");
        }
        try {
            Object o = ServiceUtil.excuteMethod(split[0], split[1], null);
            if (o == null) {
                return null;
            }
            Map<String, Object> map = (Map<String, Object>) o;
            return map.get(val);
        } catch (Exception e) {
            return null;
        }
    }
}
